import json
import time
import unittest
import re

from Base.BaseSetting import TestCases_dir
from Base.DataBase import mysqldb
from Base.Report_Result import TestResult

class info_collect():

    def get_data(self):
        self.suite = unittest.defaultTestLoader.discover(TestCases_dir,pattern='Test*.py')
        runner = unittest.TextTestRunner(resultclass=TestResult)  # 使用定制的TestResult类
        result = runner.run(self.suite)
        results = result.summary
        print(results)

        for detail in results.get('details'):
            stat_dict = results.get('stat')
            time_dict = results.get('time')

            info = detail.get('code')
            info = info.split('    ')

            info=str(info)
            author = "".join(re.findall("author = '(.+?)'...", info))
            casemodule ="".join(re.findall("module = '(.+?)'...", info))
            des = "".join(re.findall( '"""(.+?)"""',info))

            execute_sum = stat_dict.get('testsRun')
            success_num = stat_dict.get('successes')
            fail_sum = stat_dict.get('failures')
            percent = str(round(success_num / execute_sum, 4) * 100) + '%'

            test_start_time = time_dict.get('start_at')
            test_end_time = time_dict.get('end_at')
            test_duration_time = time_dict.get('duration')
            Batch_number = 'WN' + str(round(time.time()))

            date_time1 = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(test_start_time))
            date_time2 = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(test_end_time))

            date_time3 = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(detail.get('time').get('start_at')))
            date_time4 = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(detail.get('time').get('end_at')))

            fail_info = detail.get('reason')

            db = mysqldb()
            sql = """insert into woniuboss_01(batch_info,total_excount,success_cases,failed_cases,percent,start_time,end_time,count_time,case_id,case_module,case_desc,case_start_time,case_end_time,case_count_time,opetator,actual_res,failed_info) values('%s',%d,%d,%d,'%s',str_to_date(\'%s\','%%Y-%%m-%%d %%H:%%i:%%s'),str_to_date(\'%s\','%%Y-%%m-%%d %%H:%%i:%%s'),'%s','%s','%s','%s',str_to_date(\'%s\','%%Y-%%m-%%d %%H:%%i:%%s'),str_to_date(\'%s\','%%Y-%%m-%%d %%H:%%i:%%s'),'%s','%s','%s',"%s")""" % \
                   (Batch_number, execute_sum,success_num, fail_sum, percent, date_time1, date_time2, test_duration_time,
                    detail.get('name'),casemodule,des,date_time3,date_time4, detail.get('time').get('duration'), author,detail.get('status'),
                    fail_info)

            db.excute_sql(sql)


if __name__ == '__main__':
    a = info_collect()
    a.get_data()
